package edu.njust.httpmanager.interceptor;

import edu.njust.httpmanager.common.UserContext;
import edu.njust.httpmanager.constance.ResponseCode;
import edu.njust.httpmanager.entity.User;
import edu.njust.httpmanager.exception.CustomException;
import edu.njust.httpmanager.service.IUserService;
import edu.njust.httpmanager.utils.JwtUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 对请求进行拦截
 *  验证token是否有效
 */
@Slf4j
@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Resource
    private IUserService userService;

    /**
     * 处理请求前做什么
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // OPTIONS请求不会携带请求头，但需要放行
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            return true;
        }

        // 获取token
        String token = request.getHeader("Authorization");

        if (token != null && JwtUtil.validateJwtToken(token)) {
            // 放行
            Long userId = JwtUtil.getId(token);
            request.setAttribute("userId", userId);

            User user = userService.getById(userId);
            if (user == null) {
                throw new CustomException(ResponseCode.NOT_LOGIN_ERROR);
            }

            UserContext.setUser(user);
            return true;
        } else {
            // 用户未登录
            log.warn("用户未登录");
            throw new CustomException(ResponseCode.NOT_LOGIN_ERROR);
        }
    }
}
